<template>
  <view class="confirmOrder">
    <view class="address" @click="toAddressPage">
      <view class="noAddress" v-if="!defaultAddress.realName">
        <view class="text">
          <image
            src="../../static/images/confirmOrder/address.png"
            mode=""
          ></image>
          <view class="add">添加收货地址</view>
        </view>
      </view>
      <view class="haveAddress" v-else>
        <view class="nameAphone">
          <view class="name">{{ defaultAddress.realName }}</view>
          <view class="phone">{{ defaultAddress.phone }}</view>
        </view>
        <view class="address_info">{{
          defaultAddress.province +
          defaultAddress.city +
          defaultAddress.district +
          defaultAddress.detail
        }}</view>
      </view>
      <view style="width: 5%"></view>
      <u-icon class="icon" name="arrow-right" bold="true"></u-icon>
    </view>
    <view class="products">
      <template v-if="source == 'detail' || source == 'integral'">
        <view class="product">
          <image :src="baseImgUrl + goodDetail.goodImg" mode=""></image>
          <view class="product_info">
            <view class="display">
              <view class="title">{{ goodDetail.goodName }}</view>
              <view class="price" v-if="source == 'detail'"
                >￥<span class="span">{{
                  goodDetail.discountPrice
                }}</span></view
              >
            </view>
            <view class="computer" v-if="source == 'detail'">
                      <button
                type="default"
                @click="minusFun(buyNum, goodDetail.discountPrice)"
                :plain="true"
                size="mini"
              >
                <u-icon color="#000" name="minus" bold="true"></u-icon>
              </button>
             <view style="width: 60rpx; text-align: center"
                >{{ buyNum }}</view
              >
                      <button
                type="default"
                class="black"
                @click="plusFun(goodDetail.discountPrice, index)"
                :plain="true"
                size="mini"
              >
                <u-icon color="#fff" name="plus" bold="true"></u-icon>
              </button>
            </view>
            <view class="computer" v-if="source == 'integral'">
              <view style="width: 60rpx; text-align: center">*1</view>
            </view>
          </view>
        </view>
      </template>
      <template v-else>
        <view
          class="product"
          v-for="(item, index) in products"
          :key="index"
          :style="{
            'border-bottom':
              index + 1 < products.length ? '1rpx solid #c9c9c9' : 'none',
          }"
        >
          <image :src="baseImgUrl + item.goodImg"></image>
          <view class="product_info">
            <view class="display">
              <view class="title">{{ item.goodName }}</view>
              <view class="price" v-if="source == 'cart'"
                >￥<span class="span">{{ item.retailPrice }}</span></view
              >
              <view class="price" v-if="source == 'order'"
                >￥<span class="span">{{ item.goodPrice }}</span></view
              >
            </view>
            <view class="computer" v-if="source == 'cart'">
              <!--              <button
                type="default"
                @click="minusFun(item.cartNum, item.retailPrice, index)"
                :plain="true"
                size="mini"
              >
                <u-icon color="#000" name="minus" bold="true"></u-icon>
              </button> -->
              <view style="width: 60rpx; text-align: center"
                >*{{ item.cartNum }}</view
              >
              <!--         <button
                type="default"
                class="black"
                @click="plusFun(item.cartNum, item.retailPrice, index)"
                :plain="true"
                size="mini"
              >
                <u-icon color="#fff" name="plus" bold="true"></u-icon>
              </button> -->
            </view>
            <view class="computer" v-if="source == 'order'">
              <view style="width: 60rpx; text-align: center"
                >x{{ item.goodCount }}</view
              >
            </view>
          </view>
        </view>
      </template>
    </view>
    <view class="sumPrice">
      <view class="totalPrice">
        <view class="text">总价</view>
        <view class="num" v-if="source == 'integral'"
          >积分{{ goodIntegral }}+￥{{ totalPrice }}</view
        >
        <view class="num" v-else>
		<text v-if="goodIntegral>0">积分{{ goodIntegral }}+</text>
			￥{{ totalPrice.toFixed(2) }}</view>
      </view>
      <view class="shippingFee">
        <view class="text">运费</view>
        <view class="num">{{freight}}</view>
      </view>
    </view>
    <view class="bottom">
      <view class="num" v-if="source == 'integral'"
        >积分{{ goodIntegral }}+￥{{ payPrice }}</view
      >
      <view class="num" v-else>￥{{ payPrice.toFixed(2) }}</view>
      <view class="submit" @click="toPay">去支付</view>
    </view>

    <PaymentPopup
      :show="paymentPopupShow"
      :source="source"
      :isCountDown="isCountDown"
      :price="payPrice"
      :integral="goodIntegral"
      :orderId="orderId"
      @close="popupClose"
      @submit="popupSubmit"
    />
  </view>
</template>

<script>
import productApi from "@/api/product";
import addressApi from "@/api/address";
import orderApi from "@/api/order";
import payApi from "@/api/pay";
import { baseImgUrl } from "@/config";
import PaymentPopup from "@/components/payment-popup/index";
import { numberMul } from "@/utils/index";
import userApi from "@/api/user";
import login from "../../api/login";

export default {
  components: {
    PaymentPopup,
  },
  data() {
    return {
      baseImgUrl,
      source: "",
      goodId: null,
      orderId: null,
      goodDetail: {},
      defaultAddress: {},
      payMoney: 0,
      products: [],
      buyNum: 1,
      totalPrice: 0, // 商品总价
      paymentPopupShow: false,
      isCountDown: false,
      goodIntegral: 0,
      isPassword: false,
      remainingSum: 0,
	  freight:0,  //运费
	  payPrice:0  //支付总价
    };
  },
  async onLoad(options) {
    this.source = options.source;
    if (options.source == "cart") {
      this.products = uni.getStorageSync("cartProduct");
      this.calculatePrice();
      this.isCountDown = true;
    } else if (options.source == "detail") {
      this.goodId = options.id;
      this.getGoodDetail();
      this.isCountDown = true;
    } else if (options.source == "order") {
		this.goodId = options.id;
		this.goodIntegral = options.integral;
		this.totalPrice = options.price*1;
      this.orderId = options.orderId;
      this.getOrderDetail();
    } else if (options.source == "integral") {
      this.goodId = options.id;
      this.goodIntegral = options.integral;
      this.totalPrice = options.price*1;
      this.getGoodDetail();
    }
    this.getDefaultAddress();
	// 查询订单支付状态-第三方平台
	this.getOrderPayStatus(this.orderId);
	this.getCostList()
  },
  onShow() {
    let selectedAddress = uni.getStorageSync("selectedAddress");
    if (
      typeof selectedAddress == "object" &&
      Object.keys(selectedAddress).length > 0
    ) {
      this.defaultAddress = selectedAddress;
      uni.removeStorageSync("selectedAddress");
    }
    this.isPay();
    this.getUserInfo();

  },
  methods: {
	  getCostList(){
		  payApi.costList({type:1,goodId:this.goodId}).then((res) => {
			  console.log(res.rows,'ddddd');
			  if(res.rows.length >0){
				  res.rows.forEach((element) =>{
				  	if(element.endPrice > this.totalPrice&& this.totalPrice>= element.startPrice){
				  					this.freight = element.price
				  					this.payPrice = this.totalPrice*1+this.freight*1
				  				}
				  });
				  
				  if(this.totalPrice >res.rows[res.rows.length-1].endPrice){
					  this.payPrice = this.totalPrice+res.rows[res.rows.length-1].price
				  }
			  }else{
				  this.payPrice = this.totalPrice
			  }
			
			  
		  });
	  },
    getOrderPayStatus(id) {
      let params = {
        id,
      };
      payApi.getOrderPayStatus(params).then((res) => {
        let msg = JSON.parse(res.msg);
        if (msg.code == 0) {
          let data = JSON.parse(msg.data);
          if (data.status == 1) {
            uni.showLoading({
              title: "查询支付结果中···",
              mask: true,
            });
            payApi
              .balancePay({
                orderId: data.outTradeNo,
                payMode: 2, // 第三方支付
                bdmReceiveAddress: {
                  ...this.defaultAddress,
                },
              })
              .then((result) => {
                if (result.code == 200) {
                  uni.hideLoading();
                  uni.removeStorageSync("cartProduct");
                  uni.showToast({
                    title: "支付成功",
                    icon: "none",
                    mask: true,
                  });
                  this.paymentPopupShow = false;
                  setTimeout(() => {
                    uni.redirectTo({
                      url: `/subPages/myOrder/detail?id=${data.outTradeNo}`,
                    });
                  }, 1500);
                }
              });
          }
        }
      });
    },
    // 获取商品详情
    getGoodDetail() {
      productApi.getGoodDetail(this.goodId).then((res) => {
        if (res.code == 200) {
          this.goodDetail = res.data;
          console.log(this.goodDetail, "goodDetail");
          if (this.source == "integral") return;
          this.totalPrice = numberMul(this.buyNum, res.data.discountPrice);
          //   retailPrice
		  this.getCostList();
        }
      });
    },
    // 获取订单详情
    getOrderDetail() {
      let data = {
        orderId: this.orderId,
      };
      orderApi.getOrderDetail(data).then((res) => {
        if (res.code == 200) {
          this.products = res.data.appletBdmOrderItemVos;
          this.calculatePrice();
        }
      });
    },
    // 获取默认地址
    getDefaultAddress() {
      addressApi.getDefaultAddress().then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.defaultAddress = res.data;
          }
        }
      });
    },
    toAddressPage() {
      uni.navigateTo({
        url: "/subPages/mine/myAddress?source=order",
      });
    },
    isPay() {
      payApi.ifSetBalancePayCode().then((res) => {
        if (res.code == 200) {
          this.isPassword = res.data;
        }
      });
    },

    // 获取用户余额
    getUserInfo() {
      userApi.fetchUserInfo().then((res) => {
        if (res.code == 200) {
          this.remainingSum = res.user.remainingSum;
        }
      });
    },

    popupSubmit(e) {
      uni.showLoading({
        title: "正在支付···",
        mask: true,
      });
      if (e.payType == 1) {
        let data = {
          orderId: this.orderId,
          payCode: e.payCode,
          payMode: 1,
          bdmReceiveAddress: {
            ...this.defaultAddress,
          },
        };
		console.log(data,'datadatadata');
        payApi
          .balancePay(data)
          .then((res) => {
			  console.log(res.code,'222222222');
            if (res.code == 200) {
              uni.hideLoading();
              uni.removeStorageSync("cartProduct");
              uni.showToast({
                title: "支付成功！",
                icon: "none",
                mask: true,
              });
              this.paymentPopupShow = false;
              // setTimeout(() => {
                uni.redirectTo({
                  url: `/subPages/myOrder/detail?id=${res.msg}`,
                });
              // }, 1500);
            }
          })
          .catch((error ) => {
			  console.log(error );
            uni.hideLoading();
          });
      }
    },
    popupClose() {
      this.paymentPopupShow = false;
      uni.redirectTo({
        url: `/subPages/myOrder/detail?id=${this.orderId}`,
      });
    },
    toPay() {
      let data;
      if (Object.keys(this.defaultAddress).length === 0) {
        uni.showToast({
          title: "请选择收货地址",
          icon: "none",
        });
        return;
      }

      if (this.source == "order") {
        this.paymentPopupShow = true;
        return;
      }
      if (this.source == "detail" || this.source == "integral") {
        data = {
				deliveryCost:this.freight,
          bdmGoodsDto: {
            id: this.goodId,
            number: this.buyNum,
		
          },
          bdmReceiveAddress: {
            ...this.defaultAddress,
          },
        };
      }
      if (this.source == "cart") {
        let bdmCartDtos = this.products.map((item) => {
          return {
            productId: item.productId,
            cartNum: item.cartNum
          };
        });
        data = {
          bdmCartDtos,
          bdmReceiveAddress: {
            ...this.defaultAddress,
          },
        };
      }

      // if (this.totalPrice > this.remainingSum) {
      //   uni.showToast({
      //     title: "余额不足，请充值！",
      //     icon: "none",
      //   });
      //   return;
      // }

      // if (this.isPassword == false) {
      //   uni.showToast({
      //     title: "请先设置支付密码",
      //     icon: "none",
      //   });
      //   return;
      // }
      orderApi.createOrder(data).then((res) => {
        if (res.code == 200) {
          this.paymentPopupShow = true;
          this.orderId = res.data.id;
          this.payPrice = res.data.payMoney;
		  
		  
        }
      });
    },
    calculatePrice() {
      if (this.source == "cart") {
        this.totalPrice = this.products.reduce((retailPrice, item) => {
          return retailPrice + item.cartNum * item.retailPrice;
        }, 0);
      }
      if (this.source == "order") {
        this.totalPrice = this.products.reduce((goodPrice, item) => {
          return goodPrice + Number(item.goodCount) * item.goodPrice;
        }, 0);
      }
    },
    minusFun(number, price, index = 0) {
      if (number <= 1) {
        uni.showToast({
          title: "最少购买一件商品",
          icon: "none",
        });
        return;
      }
      if (this.source == "detail") {
        this.buyNum -= 1;
		
        this.totalPrice = numberMul(this.buyNum, price);
      } else {
        this.products[index].cartNum -= 1;
        this.calculatePrice();
      }
	  this.getCostList()
    },
    plusFun(price, index = 0) {

		if( this.goodDetail.inventoryVersion != 0 && this.goodDetail.inventoryVersion != null& this.goodDetail.inventoryVersion != ''){
			if(this.buyNum >= this.goodDetail.inventoryVersion ){
				uni.showToast({
				  title: `超过最大购买限制`,
				  icon: "none",
				});
				
			 return
			}
		}

      if (this.source == "detail") {
		
        this.buyNum += 1;
        this.totalPrice = numberMul(this.buyNum, price);
      } else {
        this.products[index].cartNum += 1;
        this.calculatePrice();
      }
	  this.getCostList()
    },
  },
};
</script>

<style lang="less" scoped>
.confirmOrder {
  width: 100%;
  height: 100%;
  background-color: #f8f8f8;
  padding: 0 28rpx;
  box-sizing: border-box;

  .address {
    width: 100%;
    height: 180rpx;
    background-color: #fff;
    margin-top: 15rpx;
    border-radius: 8px;
    padding: 15rpx;
    box-sizing: border-box;
    display: flex;

    .noAddress {
      width: 95%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .text {
        // width: 100%;
        height: 100%;
        display: flex;
        align-items: center;

        image {
          width: 45rpx;
          height: 45rpx;
          margin-right: 10rpx;
        }
      }
    }

    .haveAddress {
      width: 92%;
      height: 100%;

      .nameAphone {
        width: 100%;
        height: 40%;
        display: flex;
        align-items: center;
        color: #000;
        font-weight: 400;

        .name {
          margin-right: 10rpx;
        }
      }

      .address_info {
        font-size: 25rpx;
        color: #9b9b9b;
        line-height: 40rpx;
        letter-spacing: 1rpx;
      }
    }
  }

  .products {
    width: 100%;
    background-color: #fff;
    margin-top: 15rpx;
    padding: 0 20rpx;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .product {
      width: 100%;
      padding: 20rpx 0;
      height: 230rpx;
      display: flex;
      align-items: center;
      box-sizing: border-box;

      image {
        width: 180rpx;
        height: 180rpx;
        border-radius: 5px;
      }

      .product_info {
        width: calc(100% - 200rpx);
        height: 180rpx;
        padding-left: 20rpx;
        position: relative;
        display: flex;
        align-items: center;

        .display {
          height: 80%;
          width: 100%;
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .title {
            width: 100%;
            color: "#000";
            font-weight: 600;
          }

          .price {
            color: #9b9b9b;
          }
        }

        .computer {
          display: flex;
          align-items: center;
          font-size: 35rpx;
          position: absolute;
          right: 0;
          bottom: 0;

          button {
            padding: 8rpx !important;
            margin: 10rpx;
          }

          .black {
            background-color: #000;
            color: #fff;
          }
        }
      }
    }
  }

  .sumPrice {
    width: 100%;
    height: 180rpx;
    background-color: #fff;
    margin-top: 15rpx;
    border-radius: 8px;
    padding: 20rpx;
    box-sizing: border-box;
    color: #888888;
    margin-bottom: 80rpx;

    .totalPrice {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 50%;

      .num {
        color: #000;
      }
    }

    .shippingFee {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 50%;
    }
  }

  .bottom {
    width: 100%;
    height: 150rpx;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15rpx 30rpx;
    font-size: 30rpx;

    .num {
      color: #000;
      font-weight: 600;
      font-size: 35rpx;
    }

    .submit {
      width: 45%;
      height: 80rpx;
      background-color: #000;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 25px;
    }
  }

  .popup {
    width: 100%;
    height: 60vh;
    padding: 20rpx 28rpx;
    position: relative;

    .product {
      width: 100%;
      height: 12vh;
      display: flex;
      justify-content: space-around;
      align-items: center;
      flex-direction: column;
      color: #000;
      border-bottom: #dddddd 1px solid;

      .text {
        font-size: 30rpx;
      }

      .num {
        font-size: 50rpx;
        font-weight: 600;
      }

      .tooslip {
        font-size: 26rpx;

        .span {
          color: #ff4254;
        }
      }
    }

    .popup_bottom {
      border-top: 1px solid #dddddd;
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 150rpx;
      position: absolute;
      bottom: 0;
      left: 0;

      .black {
        background-color: #000;
        color: #fff;
        border-radius: 25px;
        width: 80%;
      }
    }

    .specifications {
      width: 100%;
      padding: 15rpx 10rpx;

      .specificationsi {
        width: 100%;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .left {
          display: flex;

          image {
            width: 40rpx;
            height: 40rpx;
          }
        }

        .right {
          width: 40rpx;
          height: 40rpx;

          image {
            width: 40rpx;
            height: 40rpx;
          }
        }
      }
    }
  }
}
</style>
